<template>
	<view class="fabustyle">
		<input type="text" class="fabuinput" v-model="title" />
		<button @click="fabuFn">发布</button>
	</view>
	<view>
		未完成{{num}}
	</view>
	<!-- <view>
		<view v-for="(item,index) in todosArr" key="item.id" class="todostyle">
			<label>
				<checkbox :checked="item.completed" @click="handleChange(item)" />
			</label>
			<view class="titlestyle">
				{{item.title}}
			</view>
			<button @click="delFn(item.id)" class="shanchustyle">删除</button>
		</view>
	</view> -->
	<mytodos v-for="item in todosArr" :title="item.title" :completed="item.completed" :key="item.id"
		@delFn="delFn(item.id)" @handleChange="handleChange(item)"></mytodos>
</template>
<script setup>
	import {
		computed,
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	let title = ref()
	let todosArr = ref([])
	let num = computed(() => {
		let n = todosArr.value.filter(v => v.completed == false).length
		return n
	})

	function Load() {
		uni.request({
			url: "http://localhost:3000/todos",
			method: "GET",
			success(res) {
				todosArr.value = res.data
			}
		})
	}
	Load()

	function fabuFn() {
		uni.request({
			url: "http://localhost:3000/todos",
			method: "post",
			data: {
				title: title.value,
				completed: false
			},
			success() {
				Load()
				title.value = ""
			}
		})
	}

	function delFn(id) {
		uni.request({
			url: `http://localhost:3000/todos/${id}`,
			method: "DELETE",
			success() {
				Load()
			}
		})
	}

	function handleChange(item) {
		const updateData = {
			completed: !item.completed
		};
		if (title.value) {
			updateData.title = title.value;
		}
		uni.request({
			url: `http://localhost:3000/todos/${item.id}`,
			method: "patch",
			data: updateData,
			success() {
				Load()
				title.value = ""
			},
		})
	}
</script>

<style>
	.fabuinput {
		height: 100rpx;
		width: 580rpx;
		border: 2rpx solid black;
	}

	.fabustyle {
		display: flex;
		justify-content: space-between;
	}

	/* .todostyle {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.titlestyle {
		width: 420rpx;
	} */
</style>